package com.leaf.u_spring.chapter04;

import java.util.Map;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import com.google.common.collect.Maps;

/**
 * 使用参数化的通知来记录磁道播放的次数
 */
@Aspect
public class TrackCounter {

	private Map<Integer, Integer> trackCounters = Maps.newHashMap();
	
	/**
	 * 通知playTrack()方法
	 * 
	 * 
	 * playTrack(int)指定int类型参数
	 * && args(trackNumber)指定参数
	 * 
	 * 
	 * @param trackNumber
	 */
	@Pointcut("execution(* com.leaf.u_spring.chapter02.CompactDisc.playTrack(int)) && args(trackNumber)")
	public void trackPlayed(int trackNumber){}
	
	/**
	 * 播放前为磁道计数
	 * @param trackNumber
	 */
	@Before("trackPlayed(trackNumber)")
	public void countTrack(int trackNumber){
		int currentCount = getPlayCount(trackNumber);
		trackCounters.put(trackNumber, currentCount + 1);
	}

	public int getPlayCount(int trackNumber) {
		return trackCounters.containsKey(trackNumber)?trackCounters.get(trackNumber):0;
	}
	
}
